package com.springcloud.wrapper;


import com.springcloud.support.HttpHelper;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: LinnHttpServletRequestWrapper
 * @Description: request包装类
 * @author: Linn
 * @Date: 2019年8月19日22:44:34
 */

//个人理解:该类是为了解决敏感词的 详解https://blog.csdn.net/qll19970326/article/details/80793465
public class LinnHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**覆盖父类parameterMap*/
    private Map<String, String[]> params = new HashMap<>();

    /**覆盖父类输入流*/
    private final byte[] body;

    public LinnHttpServletRequestWrapper(HttpServletRequest request){
        super(request);
        params.putAll(request.getParameterMap());
        body = HttpHelper.getJsonString(request).getBytes(Charset.forName("UTF-8"));
    }

    @Override
    public BufferedReader getReader(){
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream(){

        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

        return new ServletInputStream() {

            @Override
            public int read(){
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    /**
     * 在当前map中添加参数
     */
    public void addParameter(String name, Object value) {
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[]{(String) value});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }

    /**
     * 重写getParameter，代表参数从当前类中的map获取
     */
    @Override
    public String getParameter(String name) {
        String[]values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    /**
     * getParameterValues，代表参数从当前类中的map获取
     */
    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }

}
